{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from dotenv import load_dotenv\n",
    "\n",
    "# Load environment variables (such as API keys) from config.env\n",
    "load_dotenv('./config.env')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_groq import ChatGroq\n",
    "\n",
    "model = ChatGroq(model=\"llama3-8b-8192\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "107\n"
     ]
    }
   ],
   "source": [
    "from langchain_community.document_loaders import PyPDFLoader\n",
    "\n",
    "file_path = \"https://github.com/langchain-ai/langchain/blob/21d8d41595f444a866d43eb082f4ccd50f1a26d1/docs/docs/example_data/nke-10k-2023.pdf\"\n",
    "loader = PyPDFLoader('./nke-10k-2023.pdf')\n",
    "\n",
    "docs = loader.load()\n",
    "\n",
    "print(len(docs))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "516"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "\n",
    "text_splitter = RecursiveCharacterTextSplitter(\n",
    "    chunk_size=1000, chunk_overlap=200, add_start_index=True\n",
    ")\n",
    "all_splits = text_splitter.split_documents(docs)\n",
    "\n",
    "len(all_splits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated vectors of length 384\n",
      "\n",
      "[-0.02454092726111412, -0.11797191947698593, 0.004213633015751839, 0.018862472847104073, 0.002389131812378764, 0.09116829931735992, 0.03516404703259468, 0.012289791367948055, -0.0067251138389110565, -0.03351495787501335]\n"
     ]
    }
   ],
   "source": [
    "from langchain_community.embeddings import HuggingFaceInferenceAPIEmbeddings\n",
    "import os\n",
    "\n",
    "\n",
    "embeddings = HuggingFaceInferenceAPIEmbeddings(\n",
    "    api_key=os.environ[\"HUGGING_FACE_INFERENCE_API_KEY\"], model_name=\"sentence-transformers/all-MiniLM-l6-v2\"\n",
    ")\n",
    "\n",
    "vector_1 = embeddings.embed_query(all_splits[0].page_content)\n",
    "vector_2 = embeddings.embed_query(all_splits[1].page_content)\n",
    "\n",
    "assert len(vector_1) == len(vector_2)\n",
    "print(f\"Generated vectors of length {len(vector_1)}\\n\")\n",
    "print(vector_1[:10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.vectorstores import InMemoryVectorStore\n",
    "\n",
    "vector_store = InMemoryVectorStore(embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "ids = vector_store.add_documents(documents=all_splits)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "page_content='direct to consumer operations sell products through the following number of retail stores in the United States:\n",
      "U.S. RETAIL STORES NUMBER\n",
      "NIKE Brand factory stores 213 \n",
      "NIKE Brand in-line stores (including employee-only stores) 74 \n",
      "Converse stores (including factory stores) 82 \n",
      "TOTAL 369 \n",
      "In the United States, NIKE has eight significant distribution centers. Refer to Item 2. Properties for further information.\n",
      "2023 FORM 10-K 2' metadata={'source': './nke-10k-2023.pdf', 'page': 4, 'page_label': '5', 'start_index': 3125}\n"
     ]
    }
   ],
   "source": [
    "results = vector_store.similarity_search(\n",
    "    \"How many distribution centers does Nike have in the US?\"\n",
    ")\n",
    "\n",
    "print(results[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "page_content='Table of Contents\n",
      "PART I\n",
      "ITEM 1. BUSINESS\n",
      "GENERAL\n",
      "NIKE, Inc. was incorporated in 1967 under the laws of the State of Oregon. As used in this Annual Report on Form 10-K (this \"Annual Report\"), the terms \"we,\" \"us,\" \"our,\"\n",
      "\"NIKE\" and the \"Company\" refer to NIKE, Inc. and its predecessors, subsidiaries and affiliates, collectively, unless the context indicates otherwise.\n",
      "Our principal business activity is the design, development and worldwide marketing and selling of athletic footwear, apparel, equipment, accessories and services. NIKE is\n",
      "the largest seller of athletic footwear and apparel in the world. We sell our products through NIKE Direct operations, which are comprised of both NIKE-owned retail stores\n",
      "and sales through our digital platforms (also referred to as \"NIKE Brand Digital\"), to retail accounts and to a mix of independent distributors, licensees and sales' metadata={'source': './nke-10k-2023.pdf', 'page': 3, 'page_label': '4', 'start_index': 0}\n"
     ]
    }
   ],
   "source": [
    "results = await vector_store.asimilarity_search(\"When was Nike incorporated?\")\n",
    "\n",
    "print(results[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Score: 0.8032568608893267\n",
      "\n",
      "page_content='Table of Contents\n",
      "FISCAL 2023 NIKE BRAND REVENUE HIGHLIGHTSThe following tables present NIKE Brand revenues disaggregated by reportable operating segment, distribution channel and major product line:\n",
      "FISCAL 2023 COMPARED TO FISCAL 2022\n",
      "• NIKE, Inc. Revenues were $51.2 billion in fiscal 2023, which increased 10% and 16% compared to fiscal 2022 on a reported and currency-neutral basis, respectively.\n",
      "The increase was due to higher revenues in North America, Europe, Middle East & Africa (\"EMEA\"), APLA and Greater China, which contributed approximately 7, 6,\n",
      "2 and 1 percentage points to NIKE, Inc. Revenues, respectively.\n",
      "• NIKE Brand revenues, which represented over 90% of NIKE, Inc. Revenues, increased 10% and 16% on a reported and currency-neutral basis, respectively. This\n",
      "increase was primarily due to higher revenues in Men's, the Jordan Brand, Women's and Kids' which grew 17%, 35%,11% and 10%, respectively, on a wholesale\n",
      "equivalent basis.' metadata={'source': './nke-10k-2023.pdf', 'page': 35, 'page_label': '36', 'start_index': 0}\n"
     ]
    }
   ],
   "source": [
    "results = vector_store.similarity_search_with_score(\"What was Nike's revenue in 2023?\")\n",
    "doc, score = results[0]\n",
    "print(f\"Score: {score}\\n\")\n",
    "print(doc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "page_content='Table of Contents\n",
      "FISCAL 2023 NIKE BRAND REVENUE HIGHLIGHTSThe following tables present NIKE Brand revenues disaggregated by reportable operating segment, distribution channel and major product line:\n",
      "FISCAL 2023 COMPARED TO FISCAL 2022\n",
      "• NIKE, Inc. Revenues were $51.2 billion in fiscal 2023, which increased 10% and 16% compared to fiscal 2022 on a reported and currency-neutral basis, respectively.\n",
      "The increase was due to higher revenues in North America, Europe, Middle East & Africa (\"EMEA\"), APLA and Greater China, which contributed approximately 7, 6,\n",
      "2 and 1 percentage points to NIKE, Inc. Revenues, respectively.\n",
      "• NIKE Brand revenues, which represented over 90% of NIKE, Inc. Revenues, increased 10% and 16% on a reported and currency-neutral basis, respectively. This\n",
      "increase was primarily due to higher revenues in Men's, the Jordan Brand, Women's and Kids' which grew 17%, 35%,11% and 10%, respectively, on a wholesale\n",
      "equivalent basis.' metadata={'source': './nke-10k-2023.pdf', 'page': 35, 'page_label': '36', 'start_index': 0}\n",
      "Score: 0.7239282282727758\n",
      "\n",
      "page_content='Table of Contents\n",
      "GROSS MARGIN\n",
      "FISCAL 2023 COMPARED TO FISCAL 2022\n",
      "For fiscal 2023, our consolidated gross profit increased 4% to $22,292 million compared to $21,479 million for fiscal 2022. Gross margin decreased 250 basis points to\n",
      "43.5% for fiscal 2023 compared to 46.0% for fiscal 2022 due to the following:\n",
      "*Wholesale equivalent\n",
      "The decrease in gross margin for fiscal 2023 was primarily due to:\n",
      "• Higher NIKE Brand product costs, on a wholesale equivalent basis, primarily due to higher input costs and elevated inbound freight and logistics costs as well as\n",
      "product mix;\n",
      "• Lower margin in our NIKE Direct business, driven by higher promotional activity to liquidate inventory in the current period compared to lower promotional activity in\n",
      "the prior period resulting from lower available inventory supply;\n",
      "• Unfavorable changes in net foreign currency exchange rates, including hedges; and\n",
      "• Lower off-price margin, on a wholesale equivalent basis.\n",
      "This was partially offset by:' metadata={'source': './nke-10k-2023.pdf', 'page': 36, 'page_label': '37', 'start_index': 0}\n"
     ]
    }
   ],
   "source": [
    "embedding = embeddings.embed_query(\"How were Nike's margins impacted in 2023?\")\n",
    "\n",
    "results = vector_store.similarity_search_by_vector(embedding)\n",
    "print(results[0])\n",
    "results = vector_store.similarity_search_with_score(\"What was Nike's Gross margin in 2023?\")\n",
    "doc, score = results[0]\n",
    "print(f\"Score: {score}\\n\")\n",
    "print(doc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[Document(id='07baacd0-ff89-4111-b8bf-4cc68f3a9773', metadata={'source': './nke-10k-2023.pdf', 'page': 4, 'page_label': '5', 'start_index': 3125}, page_content='direct to consumer operations sell products through the following number of retail stores in the United States:\\nU.S. RETAIL STORES NUMBER\\nNIKE Brand factory stores 213 \\nNIKE Brand in-line stores (including employee-only stores) 74 \\nConverse stores (including factory stores) 82 \\nTOTAL 369 \\nIn the United States, NIKE has eight significant distribution centers. Refer to Item 2. Properties for further information.\\n2023 FORM 10-K 2')],\n",
       " [Document(id='8f003881-e401-422a-a804-2b64e5014fdd', metadata={'source': './nke-10k-2023.pdf', 'page': 3, 'page_label': '4', 'start_index': 0}, page_content='Table of Contents\\nPART I\\nITEM 1. BUSINESS\\nGENERAL\\nNIKE, Inc. was incorporated in 1967 under the laws of the State of Oregon. As used in this Annual Report on Form 10-K (this \"Annual Report\"), the terms \"we,\" \"us,\" \"our,\"\\n\"NIKE\" and the \"Company\" refer to NIKE, Inc. and its predecessors, subsidiaries and affiliates, collectively, unless the context indicates otherwise.\\nOur principal business activity is the design, development and worldwide marketing and selling of athletic footwear, apparel, equipment, accessories and services. NIKE is\\nthe largest seller of athletic footwear and apparel in the world. We sell our products through NIKE Direct operations, which are comprised of both NIKE-owned retail stores\\nand sales through our digital platforms (also referred to as \"NIKE Brand Digital\"), to retail accounts and to a mix of independent distributors, licensees and sales')]]"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from typing import List\n",
    "\n",
    "from langchain_core.documents import Document\n",
    "from langchain_core.runnables import chain\n",
    "\n",
    "\n",
    "@chain\n",
    "def retriever(query: str) -> List[Document]:\n",
    "    return vector_store.similarity_search(query, k=1)\n",
    "\n",
    "\n",
    "retriever.batch(\n",
    "    [\n",
    "        \"How many distribution centers does Nike have in the US?\",\n",
    "        \"When was Nike incorporated?\",\n",
    "    ],\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
